import type {
  ComponentRecordType,
  GenerateMenuAndRoutesOptions,
  RouteRecordStringComponent,
} from '@vben/types';

import { generateAccessible } from '@vben/access';
import { preferences } from '@vben/preferences';

import { ElMessage } from 'element-plus';

import { getAllMenusApi } from '#/api';
import { BasicLayout, IFrameView } from '#/layouts';
import { $t } from '#/locales';

const forbiddenComponent = () => import('#/views/_core/fallback/forbidden.vue');

// 简化版转换函数，确保所有字段都是基本类型
function transformMenuData(menuData: any[]): RouteRecordStringComponent[] {
  if (!Array.isArray(menuData)) {
    return [];
  }

  // 使用简单的计数器避免名称冲突
  const nameCount: Record<string, number> = {};

  function getUniqueName(baseName = 'route'): string {
    if (!nameCount[baseName]) {
      nameCount[baseName] = 1;
      return baseName;
    }
    return `${baseName}${++nameCount[baseName]}`;
  }

  function processItem(item: any, isChild = false): RouteRecordStringComponent {
    // 确保所有字段都是基本类型
    const name = getUniqueName(
      typeof item.name === 'string' ? item.name : 'route',
    );

    // 确保路径是字符串
    let path = '';
    if (typeof item.path === 'string') {
      path = item.path;
    } else if (item.path !== null && item.path !== undefined) {
      path = String(item.path);
    } else {
      path = isChild ? 'unknown' : '/unknown';
    }

    // 子路由不应该以 / 开头
    if (isChild && path.startsWith('/')) {
      path = path.slice(1);
    }

    // 根路由应该以 / 开头
    if (!isChild && !path.startsWith('/')) {
      path = `/${path}`;
    }

    // 确保组件是字符串
    let component = 'default';
    if (item.component === 'Layout') {
      component = 'Layout';
    } else if (typeof item.component === 'string' && item.component) {
      component = item.component;
    }

    const route: RouteRecordStringComponent = {
      name,
      path,
      component,
      meta: {
        title: typeof item.meta?.title === 'string' ? item.meta.title : name,
        icon: typeof item.meta?.icon === 'string' ? item.meta.icon : undefined,
        noCache:
          typeof item.meta?.noCache === 'boolean' ? item.meta.noCache : true,
        link: typeof item.meta?.link === 'string' ? item.meta.link : undefined,
        hideInMenu: typeof item.hidden === 'boolean' ? item.hidden : false,
      },
    };

    // 处理重定向
    if (
      item.redirect &&
      item.redirect !== 'noRedirect' &&
      typeof item.redirect === 'string'
    ) {
      route.redirect = item.redirect;
    }

    // 处理 alwaysShow
    if (item.alwaysShow === true && route.meta) {
      route.meta.alwaysShow = true;
    }

    // 处理子路由
    if (Array.isArray(item.children) && item.children.length > 0) {
      route.children = item.children.map((child: any) =>
        processItem(child, true),
      );
    }

    return route;
  }

  return menuData.map((item) => processItem(item));
}

async function generateAccess(options: GenerateMenuAndRoutesOptions) {
  // console.log('generateAccess function called');
  // console.log('Current access mode:', preferences.app.accessMode);

  const pageMap: ComponentRecordType = import.meta.glob('../views/**/*.vue');

  const layoutMap: ComponentRecordType = {
    BasicLayout,
    IFrameView,
    Layout: BasicLayout,
  };

  return await generateAccessible(preferences.app.accessMode, {
    ...options,
    fetchMenuListAsync: async () => {
      // console.log('fetchMenuListAsync is being executed!');
      ElMessage({
        duration: 1500,
        message: `${$t('common.loadingMenu')}...`,
      });
      try {
        const result = await getAllMenusApi();
        // console.log('Fetched menu data:', result);

        const rawData = result.data || result;
        const menuData = transformMenuData(rawData);
        // console.log('Transformed menu data:', menuData);

        return menuData;
      } catch (error) {
        console.error('Failed to fetch menu data:', error);
        ElMessage({
          type: 'error',
          message: `${$t('common.loadingMenuFailed')}`,
        });
        return [];
      }
    },
    forbiddenComponent,
    layoutMap,
    pageMap,
  });
}

export { generateAccess };
